package com.forcht.server.handler.impl;

import com.forcht.common.domain.*;
import com.forcht.common.enumeration.ResponseCode;
import com.forcht.common.enumeration.ResponseType;
import com.forcht.common.util.ProtostuffUtil;
import com.forcht.server.dao.ChatOneDao;
import com.forcht.server.handler.MessageHandler;
import com.forcht.server.handler.UserHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.List;

/**
 * Created by forcht on 2018/4/14.
 */
@Component("messageHandler.login")
public class LoginMessageHandler extends MessageHandler {

    @Autowired
    private UserHandler userHandler;
    @Autowired
    private ChatOneDao chatOneDao;
    @Override
    public void handle(Message message,SelectionKey key) {
        System.out.println("服务器接收到客户端发送的数据：" + message);
        //解析消息
        SocketChannel socketChannel=(SocketChannel)key.channel();
        MessageHeader header = message.getHeader();
        String username = header.getSender();
        byte[] password = message.getBody();
        User user = userHandler.login(socketChannel, username, new String(password));
        //服务器响应客户端的请求
        Response response;
        if(user!=null){
            response = Response.builder().header(
                    ResponseHeader.builder()
                            .responseCode(ResponseCode.LOGIN_SUCCESS)
                            .responseType(ResponseType.HINT)
                            .timestamp(new Date()).build()).body(ProtostuffUtil.serialize(user)).build();
        }else{
            response = Response.builder().header(
                    ResponseHeader.builder()
                            .responseCode(ResponseCode.LOGIN_FAIL)
                            .responseType(ResponseType.HINT)
                            .timestamp(new Date()).build()).body("登录失败".getBytes()).build();
        }
        try {
            socketChannel.write(ByteBuffer.wrap(ProtostuffUtil.serialize(response)));
            if(user!=null){
                //查找未登录时有哪些用户发送过信息
                List<ChatOne> chatOnes = chatOneDao.selectSenders(username);
                for(int i=0;i<chatOnes.size();i++){
                    //分别查找出每个用户的信息
                    List<ChatOne> list = chatOneDao.selectChatContent(chatOnes.get(i).getSender(), username);
                    for(int j=0;j<list.size();j++){
                        Response receiverResponse = Response.builder().header(
                                ResponseHeader.builder()
                                        .sender(chatOnes.get(i).getSender())
                                        .responseType(ResponseType.MESSAGE)
                                        .responseCode(ResponseCode.CHAT_ONE)
                                        .timestamp(new Date()).build()).body(list.get(j).getContent().getBytes()).build();
                        System.out.println(receiverResponse);
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        socketChannel.write(ByteBuffer.wrap(ProtostuffUtil.serialize(receiverResponse)));
                    }

                }
                //广播通知好友上线
                userHandler.broadcast(user,ResponseCode.FRIEND_LOGIN);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
